package com.base.controller.api;

import com.base.comm.CommContent;
import com.base.controller.utils.OrionUtil;
import com.base.helper.*;
import com.base.po.acess.AcessToken;
import com.base.po.acess.TokenUtils;
import com.base.po.param.LJSms;
import com.base.po.param.NetState;
import com.base.po.param.Sms;
import com.base.po.param.VosModelList;
import com.base.po.voip.*;
import com.base.service.*;
import com.base.utils.GsonUtil;
import com.base.utils.IP;
import com.base.utils.PasswordUtils;
import com.base.utils.Produce;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

/**
 * 客户端用户操作
 *
 * @author Administrator
 */
@Slf4j
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private ApiinfoesService apiinfoesService;
    @Autowired
    private SubscribersService subscribersService;
    @Autowired
    private SmsconfigsService smsconfigsService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private AttributionsService attributionsService;
    @Autowired
    private RegisterinfoesService registerinfoesService;
    @Autowired
    private SmsinfoesService smsinfoesService;
    @Autowired
    private PayinfoesService payinfoesService;
    @Autowired
    private ShareService shareService;
    @Autowired
    private RewardsService rewardsService;
    @Autowired
    private ChangeRecordService changeRecordService;
    @Autowired
    private LogsService logsService;// log日志
    @Autowired
    private ShareRedPacketService shareRedPacketService;
    @Autowired
    private ShareRedPacketLogService shareRedPacketLogService;
    @Autowired
    private ShareRedPacketMoneyService shareRedPacketMoneyService;
    @Autowired
    private InviteCodeService inviteCodeService;

    private static final Object obj = new Object(); //对象锁，注册专用

    // 进入注册页面
    @RequestMapping(value = "/text")
    public String text() {
        return "jsp/wap_register";
    }

    // 进入分享注册页面
    @RequestMapping(value = "/shareIndex")
    public String shareIndex(HttpServletRequest request, String userid, String invitecode) {
        if (userid == null && userid.equals("") && invitecode == null && invitecode.equals("")) {
            return "jsp/wap_share_register";
        }

        // 用户id
        String uId = null;
        if (userid != null) {
            uId = userid;
        } else {
            List<InviteCode> code = inviteCodeService.selectByCode(invitecode);
            if (code != null && code.size() > 0) {
                uId = code.get(0).getUserid();
            } else {
                return "jsp/wap_share_register";
            }
        }

        Subscribers subscribers = subscribersService.selectByPrimaryKey(uId);
        List<Share> share = shareService.selectTypeTwoByParentId(subscribers.getParentid());
        request.setAttribute("userid", uId);
        if (share != null && share.size() > 0) {
            request.setAttribute("sharepic", share.get(0).getSharepic());
        }
        request.setAttribute("parentid", subscribers.getParentid());

        if (subscribers.getParentid().equals("0b8a2f00271e40b9aea750264bf1bb58")) {
            return "jsp/wap_share_register_new";
        }
        return "jsp/wap_share_register";
    }

    // 进入分享下载页面
    @RequestMapping(value = "/shareDownload")
    public String shareDownload(HttpServletRequest request, String userid) {
        if (userid == null || userid.equals("")) {
            return "jsp/wap_share_download";
        }
        Subscribers subscribers = subscribersService.selectByPrimaryKey(userid);
        List<Share> share = shareService.selectTypeThreeByParentId(subscribers.getParentid());
        Users u = usersService.selectByPrimaryKey(subscribers.getParentid());
        if (share != null && share.size() > 0) {
            request.setAttribute("sharepic", share.get(0).getSharepic());
        }
        request.setAttribute("iospath", u.getIospath());
        request.setAttribute("androidpath", u.getAndroidpath());
        if (subscribers.getParentid().equals("58162318-deca-4442-8e38-743b7729aa5b")) {
            request.setAttribute("parentid", 2);
        } else {
            request.setAttribute("parentid", 1);
        }
        return "jsp/wap_share_download";
    }

    // 验证用户是否真实存在
    @CrossOrigin
    @RequestMapping(value = "/checkUser", method = RequestMethod.POST)
    public @ResponseBody
    NetState checkUser(HttpServletRequest request) {
        // 返回数据对象
        NetState netState = new NetState();
        String AuthorizationToken = request.getHeader("SDB-Authorization");
        AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
        if (acessToken == null || acessToken.equals("")) {
            netState.setData("数据签名错误");
            netState.setErrorCode(NetState.SIGN_ERROR);
        } else {
            String Mobile = acessToken.getMobile();
            String ParentId = acessToken.getParentid();
            // 验证参数
            if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("客户端参数错误");
            } else {
                SubscribersExample subscribersExample = new SubscribersExample();
                subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(Mobile)
                        .andParentidEqualTo(ParentId).andDatastatusEqualTo(true));
                List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
                if (subscribers != null && subscribers.size() > 0) {
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setData("true");
                } else {
                    netState.setErrorCode(NetState.ACCOUNT_ERROR);
                    netState.setData("false");
                }
            }
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "验证用户是否真实存在");
//        apiinfoesService.insert(
//                ApiinfoesHelper.setApiinfoes(apiinfoes, AuthorizationToken, GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 获取验证码 判断用户是否存在的，若用户不存在，返回1001或者1002
    @CrossOrigin
    @RequestMapping(value = "/smsReInfo", method = RequestMethod.POST)
    public @ResponseBody
    NetState smsReInfo(HttpServletRequest request, String Mobile, String ParentId, Integer type) throws Exception {
        NetState netState = new NetState();

        Boolean isSend = false;

        if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            Boolean isMobile = Produce.isMobile(Mobile);
            if (isMobile == false) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请填写正确手机号");
                return netState;
            }

            // 代理商信息
            Users users = usersService.selectByPrimaryKey(ParentId);
            // 短信信息
            SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
            smsconfigsExample.getOredCriteria()
                    .add(smsconfigsExample.createCriteria().andAgentidEqualTo(ParentId).andDatastatusEqualTo(true));
            List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
            Smsconfigs sms = s.get(0);
            switch (users.getSmstype()) {
                case 1:
                    if (s == null || s.size() == 0) {
                        netState.setErrorCode(NetState.NODATA);
                        netState.setData("该代理未配置短信通道");
                    } else {
                        if (sms.getCount() <= 0) {
                            netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                            netState.setData("验证码发送失败");
                        } else {
                            Random rand = new Random();
                            int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                            String jsondata = SmsHelper.SendSms(Mobile, num, sms.getLayid(), sms.getSignid(), sms.getType());
                            String result = WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(), null);
                            Sms sms2 = GsonUtil.getObject(result, Sms.class);
                            System.out.println(JSONObject.fromObject(sms2));
                            if (sms2.status == 0) {
                                int no = Integer.parseInt(Mobile.substring(0, 7));
                                AttributionsExample attributionsExample = new AttributionsExample();
                                attributionsExample.getOredCriteria()
                                        .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                                List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                                String address = null;
                                if (attributions == null || attributions.size() == 0) {
                                    address = "未知归属地";
                                } else {
                                    address = attributions.get(0).getCity();
                                }
                                smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"status\":\"" + sms2.status
                                        + "\",\"desc\":\"" + sms2.desc + "\",\"smsid\":\"" + sms2.smsId + "\"}");
                                sms.setCount(sms.getCount() - 1);
                                smsconfigsService.updateByPrimaryKey(sms);
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("短信发送成功");
                                netState.setJson(num);
                                isSend = true;
                            } else {
                                netState.setErrorCode(NetState.SYSTEM_ERROR);
                                netState.setData("短信发送失败,可能是您的操作过于频繁");
                            }
                        }
                    }
                    break;
                case 2:
                    if (sms.getCount() <= 0) {
                        netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                        netState.setData("验证码发送失败");
                    } else {
                        Random rand = new Random();
                        int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                        if (users.getId().equals("ffaecb8666d84a86b7e1c9792ef1c689")) {
                            users.setUsername("余乐宝");
                        }
                        String result = LJSmsHelper.sendSms(Mobile, users.getUsername(), num);
                        System.out.println("短信发送接受:" + result);
                        JSONObject obj = JSONObject.fromObject(result);
                        LJSms ljSms = (LJSms) JSONObject.toBean(obj, LJSms.class);
                        if (ljSms.getResult().equals("000")) {
                            int no = Integer.parseInt(Mobile.substring(0, 7));
                            AttributionsExample attributionsExample = new AttributionsExample();
                            attributionsExample.getOredCriteria()
                                    .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                            List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                            String address = null;
                            if (attributions == null || attributions.size() == 0) {
                                address = "未知归属地";
                            } else {
                                address = attributions.get(0).getCity();
                            }
                            smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"result\":\"" + ljSms.getResult()
                                    + "\",\"desc\":\"" + ljSms.getDesc() + "\",\"smsid\":\"" + ljSms.getSmsId() + "\"}");
                            sms.setCount(sms.getCount() - 1);
                            smsconfigsService.updateByPrimaryKey(sms);
                            netState.setErrorCode(NetState.SUCCESS_CONN);
                            netState.setData("短信发送成功");
                            netState.setJson(num);
                            isSend = true;
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("短信发送失败,可能是您的操作过于频繁");
                        }
                    }
                    break;
                case 3:
                    if (sms.getCount() <= 0) {
                        netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                        netState.setData("验证码发送失败");
                    } else {
                        Random rand = new Random();
                        int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                        if (users.getId().equals("ffaecb8666d84a86b7e1c9792ef1c689")) {
                            users.setUsername("余乐宝");
                        }
                        String result = RYSmsHelper.sendSms(Mobile, users.getUsername(), num);
                        System.out.println("短信发送接受:" + result);

                        if (result.equals("0")) {
                            int no = Integer.parseInt(Mobile.substring(0, 7));
                            AttributionsExample attributionsExample = new AttributionsExample();
                            attributionsExample.getOredCriteria()
                                    .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                            List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                            String address = null;
                            if (attributions == null || attributions.size() == 0) {
                                address = "未知归属地";
                            } else {
                                address = attributions.get(0).getCity();
                            }
                            smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"result\":\"" + 0
                                    + "\",\"desc\":\"成功\",\"smsid\":\"" + result + "\"}");
                            sms.setCount(sms.getCount() - 1);
                            smsconfigsService.updateByPrimaryKey(sms);
                            netState.setErrorCode(NetState.SUCCESS_CONN);
                            netState.setData("短信发送成功");
                            netState.setJson(num);
                            isSend = true;
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("短信发送失败,可能是您的操作过于频繁");
                        }
                    }
                    break;
            }
        }


        List<Subscribers> isExist = subscribersService.selectBySub(Mobile, ParentId);
        if (isExist.isEmpty()) {
            netState.setErrorCode(NetState.LOGIN_UNREGISTERED);
        } else {
            netState.setErrorCode(NetState.LOGIN_REGISTERED);
        }

//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "短信验证");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(ParentId, Mobile),
//                GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 获取验证码
    @CrossOrigin
    @RequestMapping(value = "/smsInfo", method = RequestMethod.POST)
    public @ResponseBody
    NetState smsInfo(HttpServletRequest request, String Mobile, String ParentId, Integer type) throws Exception {
        NetState netState = new NetState();
        log.warn("mobile={},parentid={}", Mobile, ParentId);
        Boolean isSend = false;

        if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            Boolean isMobile = Produce.isMobile(Mobile);
            if (isMobile == false) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请填写正确手机号");
                return netState;
            }

            // 代理商信息
            Users users = usersService.selectByPrimaryKey(ParentId);
            // 短信信息
            SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
            smsconfigsExample.getOredCriteria()
                    .add(smsconfigsExample.createCriteria().andAgentidEqualTo(ParentId).andDatastatusEqualTo(true));
            List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
            Smsconfigs sms = s.get(0);
            switch (users.getSmstype()) {
                case 1:
                    if (s == null || s.size() == 0) {
                        netState.setErrorCode(NetState.NODATA);
                        netState.setData("该代理未配置短信通道");
                    } else {
                        if (sms.getCount() <= 0) {
                            netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                            netState.setData("验证码发送失败");
                        } else {
                            Random rand = new Random();
                            int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                            String jsondata = SmsHelper.SendSms(Mobile, num, sms.getLayid(), sms.getSignid(), sms.getType());
                            String result = WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(), null);
                            Sms sms2 = GsonUtil.getObject(result, Sms.class);
                            System.out.println(JSONObject.fromObject(sms2));
                            if (sms2.status == 0) {
                                int no = Integer.parseInt(Mobile.substring(0, 7));
                                AttributionsExample attributionsExample = new AttributionsExample();
                                attributionsExample.getOredCriteria()
                                        .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                                List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                                String address = null;
                                if (attributions == null || attributions.size() == 0) {
                                    address = "未知归属地";
                                } else {
                                    address = attributions.get(0).getCity();
                                }
                                smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"status\":\"" + sms2.status
                                        + "\",\"desc\":\"" + sms2.desc + "\",\"smsid\":\"" + sms2.smsId + "\"}");
                                sms.setCount(sms.getCount() - 1);
                                smsconfigsService.updateByPrimaryKey(sms);
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("短信发送成功");
                                netState.setJson(num);
                                isSend = true;
                            } else {
                                netState.setErrorCode(NetState.SYSTEM_ERROR);
                                netState.setData("短信发送失败,可能是您的操作过于频繁");
                            }
                        }
                    }
                    break;
                case 2:
                    if (sms.getCount() <= 0) {
                        netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                        netState.setData("验证码发送失败");
                    } else {
                        Random rand = new Random();
                        int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                        if (users.getId().equals("ffaecb8666d84a86b7e1c9792ef1c689")) {
                            users.setUsername("余乐宝");
                        }
                        String result = LJSmsHelper.sendSms(Mobile, users.getUsername(), num);
                        System.out.println("短信发送接受:" + result);
                        JSONObject obj = JSONObject.fromObject(result);
                        LJSms ljSms = (LJSms) JSONObject.toBean(obj, LJSms.class);
                        if (ljSms.getResult().equals("000")) {
                            int no = Integer.parseInt(Mobile.substring(0, 7));
                            AttributionsExample attributionsExample = new AttributionsExample();
                            attributionsExample.getOredCriteria()
                                    .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                            List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                            String address = null;
                            if (attributions == null || attributions.size() == 0) {
                                address = "未知归属地";
                            } else {
                                address = attributions.get(0).getCity();
                            }
                            smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"result\":\"" + ljSms.getResult()
                                    + "\",\"desc\":\"" + ljSms.getDesc() + "\",\"smsid\":\"" + ljSms.getSmsId() + "\"}");
                            sms.setCount(sms.getCount() - 1);
                            smsconfigsService.updateByPrimaryKey(sms);
                            netState.setErrorCode(NetState.SUCCESS_CONN);
                            netState.setData("短信发送成功");
                            netState.setJson(num);
                            isSend = true;
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("短信发送失败,可能是您的操作过于频繁");
                        }
                    }
                    break;
                case 3:
                    if (sms.getCount() <= 0) {
                        netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                        netState.setData("验证码发送失败");
                    } else {
                        Random rand = new Random();
                        int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                        if (users.getId().equals("ffaecb8666d84a86b7e1c9792ef1c689")) {
                            users.setUsername("余乐宝");
                        }
                        String result = RYSmsHelper.sendSms(Mobile, users.getUsername(), num);
                        System.out.println("短信发送接受:" + result);

                        if (result.equals("0")) {
                            int no = Integer.parseInt(Mobile.substring(0, 7));
                            AttributionsExample attributionsExample = new AttributionsExample();
                            attributionsExample.getOredCriteria()
                                    .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                            List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                            String address = null;
                            if (attributions == null || attributions.size() == 0) {
                                address = "未知归属地";
                            } else {
                                address = attributions.get(0).getCity();
                            }
                            smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"result\":\"" + 0
                                    + "\",\"desc\":\"成功\",\"smsid\":\"" + result + "\"}");
                            sms.setCount(sms.getCount() - 1);
                            smsconfigsService.updateByPrimaryKey(sms);
                            netState.setErrorCode(NetState.SUCCESS_CONN);
                            netState.setData("短信发送成功");
                            netState.setJson(num);
                            isSend = true;
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("短信发送失败,可能是您的操作过于频繁");
                        }
                    }
                    break;
            }
        }


        if ((ParentId.equals("58162318-deca-4442-8e38-743b7729aa5b") || ParentId.equals("d22ee665979346dcb1ffdcad4a942129") || ParentId.equals("c10fcd0eafb44ba28d6d3125b47e59c9") || ParentId.equals("dcd3a5667d3742d1a6b44e1ccdca7b31")) && type != null && type == 1 && isSend) {
            List<Subscribers> isExist = subscribersService.selectBySub(Mobile, ParentId);
            if (isExist.isEmpty()) {
                netState.setErrorCode(NetState.LOGIN_UNREGISTERED);
            } else {
                netState.setErrorCode(NetState.LOGIN_REGISTERED);
            }
        }

//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "短信验证");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(ParentId, Mobile),
//                GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 获取验证码
    @RequestMapping(value = "/smsInfoForRegister", method = RequestMethod.POST)
    public @ResponseBody
    NetState smsInfoForRegister(HttpServletRequest request, String Mobile, String ParentId, Integer type) throws Exception {
        NetState netState = new NetState();

        Boolean isSend = false;

        if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            Boolean isMobile = Produce.isMobile(Mobile);
            if (isMobile == false) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请填写正确手机号");
                return netState;
            }

            // 代理商信息
            Users users = usersService.selectByPrimaryKey(ParentId);
            // 短信信息
            SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
            smsconfigsExample.getOredCriteria()
                    .add(smsconfigsExample.createCriteria().andAgentidEqualTo(ParentId).andDatastatusEqualTo(true));
            List<Smsconfigs> s = smsconfigsService.selectByExample(smsconfigsExample);
            Smsconfigs sms = s.get(0);
            switch (users.getSmstype()) {
                case 1:
                    if (s == null || s.size() == 0) {
                        netState.setErrorCode(NetState.NODATA);
                        netState.setData("该代理未配置短信通道");
                    } else {
                        if (sms.getCount() <= 0) {
                            netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                            netState.setData("验证码发送失败");
                        } else {
                            Random rand = new Random();
                            int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                            String jsondata = SmsHelper.SendSms(Mobile, num, sms.getLayid(), sms.getSignid(), sms.getType());
                            String result = WebHelper.PostData(sms.getUrl(), jsondata, sms.getContenttype(), null);
                            Sms sms2 = GsonUtil.getObject(result, Sms.class);
                            System.out.println(JSONObject.fromObject(sms2));
                            if (sms2.status == 0) {
                                int no = Integer.parseInt(Mobile.substring(0, 7));
                                AttributionsExample attributionsExample = new AttributionsExample();
                                attributionsExample.getOredCriteria()
                                        .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                                List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                                String address = null;
                                if (attributions == null || attributions.size() == 0) {
                                    address = "未知归属地";
                                } else {
                                    address = attributions.get(0).getCity();
                                }
                                smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"status\":\"" + sms2.status
                                        + "\",\"desc\":\"" + sms2.desc + "\",\"smsid\":\"" + sms2.smsId + "\"}");
                                sms.setCount(sms.getCount() - 1);
                                smsconfigsService.updateByPrimaryKey(sms);
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("短信发送成功");
                                netState.setJson(num);
                                isSend = true;
                            } else {
                                netState.setErrorCode(NetState.SYSTEM_ERROR);
                                netState.setData("短信发送失败,可能是您的操作过于频繁");
                            }
                        }
                    }
                    break;
                case 2:
                    if (sms.getCount() <= 0) {
                        netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                        netState.setData("验证码发送失败");
                    } else {
                        Random rand = new Random();
                        int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                        if (users.getId().equals("ffaecb8666d84a86b7e1c9792ef1c689")) {
                            users.setUsername("余乐宝");
                        }
                        String result = LJSmsHelper.sendSms(Mobile, users.getUsername(), num);
                        System.out.println("短信发送接受:" + result);
                        JSONObject obj = JSONObject.fromObject(result);
                        LJSms ljSms = (LJSms) JSONObject.toBean(obj, LJSms.class);
                        if (ljSms.getResult().equals("000")) {
                            int no = Integer.parseInt(Mobile.substring(0, 7));
                            AttributionsExample attributionsExample = new AttributionsExample();
                            attributionsExample.getOredCriteria()
                                    .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                            List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                            String address = null;
                            if (attributions == null || attributions.size() == 0) {
                                address = "未知归属地";
                            } else {
                                address = attributions.get(0).getCity();
                            }
                            smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"result\":\"" + ljSms.getResult()
                                    + "\",\"desc\":\"" + ljSms.getDesc() + "\",\"smsid\":\"" + ljSms.getSmsId() + "\"}");
                            sms.setCount(sms.getCount() - 1);
                            smsconfigsService.updateByPrimaryKey(sms);
                            netState.setErrorCode(NetState.SUCCESS_CONN);
                            netState.setData("短信发送成功");
                            netState.setJson(num);
                            isSend = true;
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("短信发送失败,可能是您的操作过于频繁");
                        }
                    }
                    break;
                case 3:
                    if (sms.getCount() <= 0) {
                        netState.setErrorCode(NetState.AMOUNT_NOT_QUERY);
                        netState.setData("验证码发送失败");
                    } else {
                        Random rand = new Random();
                        int num = rand.nextInt(9999 - 1001 + 1) + 1001;
                        if (users.getId().equals("ffaecb8666d84a86b7e1c9792ef1c689")) {
                            users.setUsername("余乐宝");
                        }
                        String result = RYSmsHelper.sendSms(Mobile, users.getUsername(), num);
                        System.out.println("短信发送接受:" + result);

                        if (result.equals("0")) {
                            int no = Integer.parseInt(Mobile.substring(0, 7));
                            AttributionsExample attributionsExample = new AttributionsExample();
                            attributionsExample.getOredCriteria()
                                    .add(attributionsExample.createCriteria().andSectionnoEqualTo(no));
                            List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                            String address = null;
                            if (attributions == null || attributions.size() == 0) {
                                address = "未知归属地";
                            } else {
                                address = attributions.get(0).getCity();
                            }
                            smsinfoesService.insert(Mobile, num, 1, address, ParentId, "{\"result\":\"" + 0
                                    + "\",\"desc\":\"成功\",\"smsid\":\"" + result + "\"}");
                            sms.setCount(sms.getCount() - 1);
                            smsconfigsService.updateByPrimaryKey(sms);
                            netState.setErrorCode(NetState.SUCCESS_CONN);
                            netState.setData("短信发送成功");
                            netState.setJson(num);
                            isSend = true;
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("短信发送失败,可能是您的操作过于频繁");
                        }
                    }
                    break;
            }
        }

        if (type != null && type == 1 && isSend) {
            List<Subscribers> isExist = subscribersService.selectBySub(Mobile, ParentId);
            if (isExist.isEmpty()) {
                netState.setErrorCode(NetState.LOGIN_UNREGISTERED);
            } else {
                netState.setErrorCode(NetState.LOGIN_REGISTERED);
            }
        }

//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "短信验证");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(ParentId, Mobile),
//                GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 短信验证
    @RequestMapping(value = "/boofalg", method = RequestMethod.POST)
    public @ResponseBody
    int boofalg(String tel_check, String Mobile, String ParentID) {
        List<Smsinfoes> smsinfoes = smsinfoesService.selectByAgentIDAndMobile(ParentID, Mobile);
        if (smsinfoes != null && smsinfoes.size() > 0) {
            // 查询手机号 收到的最后一条接收成功的 验证码 进行比对

            try {
                if (smsinfoes.get(0).getNum().equals(Integer.parseInt(tel_check))) {
                    return 0;
                }
            } catch (NumberFormatException e) {
                return 1;
            }
        }

//		if (tel_check.equals(flag) && Mobile.equals(flagMobile)) { // 验证码正确
//			return 0;
//		}
        return 1; // 错误
    }

    // 注册信息 赠送
    @RequestMapping(value = "/registerMoney", method = RequestMethod.POST)
    public @ResponseBody
    NetState registerMoney(HttpServletRequest request, String Mobile, String ParentId,
                           String Money) {
        String Password = Mobile;
        // 返回数据对象
        NetState netState = new NetState();
        // 验证参数
        if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            Boolean isMobile = Produce.isMobile(Mobile);
            if (isMobile == false) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请填写正确手机号");
                return netState;
            }
            SubscribersExample subscribersExample = new SubscribersExample();
            subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(Mobile)
                    .andParentidEqualTo(ParentId).andDatastatusEqualTo(true));
            List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
            if (subscribers != null && subscribers.size() > 0) {
                netState.setErrorCode(NetState.DATA_RE);
                netState.setData("该账号已注册，如果您忘记密码，请在登录页点击忘记密码");
            } else {
                UsersExample usersExample = new UsersExample();
                usersExample.getOredCriteria()
                        .add(usersExample.createCriteria().andIdEqualTo(ParentId).andDatastatusEqualTo(true));
                List<Users> agents = usersService.selectByExample(usersExample);
                if (agents == null || agents.size() == 0) {
                    netState.setErrorCode(NetState.ACCOUNT_ERROR);
                    netState.setData("该代理不存在");
                } else {
                    Users agent = agents.get(0);
                    Integer mon = 0;
                    if (agent.getBlance().intValue() >= agent.getRegimoney()) {
                        mon = agent.getRegimoney();
                    } else {
                        mon = 0;
                    }
                    System.out.println("充值赠送购物余额:" + Money);
                    // VOS创建用户
                    if (VosHelper.Register(agent.getAgentprefix() + Mobile, agent.getUsername(),
                            Produce.plusDay(agent.getRegitime(), Produce.getNowDate()).getTime() + "", mon + "",
                            agent.getFreeroute())) {
                        // 创建用户
                        int result = subscribersService.insert(PasswordUtils.toPWD(Password), Produce.getNowDate(),
                                IP.getIpAddr(request), 4, true, Mobile, ParentId,
                                Produce.plusDay(365, Produce.getNowDate()), "/Images/logo.png", 7,
                                agents.get(0).getId(), "1", null, null, false, Integer.parseInt(Money),
                                new SimpleDateFormat("yyyy-MM-dd")
                                        .format(Produce.plusDay(agent.getRegitime(), Produce.getNowDate())),
                                null, "0", null, null, null, false, false, false);
                        int num = Integer.parseInt(Mobile.substring(0, 7));
                        AttributionsExample attributionsExample = new AttributionsExample();
                        attributionsExample.getOredCriteria()
                                .add(attributionsExample.createCriteria().andSectionnoEqualTo(num));
                        List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                        String address = null;
                        if (attributions == null || attributions.size() == 0) {
                            address = "未知归属地";
                        } else {
                            address = attributions.get(0).getCity();
                        }
                        if (result > 0) {
                            // TODO 整改IP获取的address，
                            int resultR = registerinfoesService.insert(Mobile, IP.getIpAddr(request), address, ParentId,
                                    address, true);
                            if (resultR > 0) {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("注册成功");
                            } else {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("注册成功,但是在获取存储您的信息时候出现了一些问题");
                            }
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("注册失败");
                        }
                    } else {
                        netState.setErrorCode(NetState.SYSTEM_ERROR);
                        netState.setData("注册失败");
                    }
                }
            }
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "注册");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(Mobile, ParentId),
//                GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 分享注册
    @RequestMapping(value = "/shareRegister", method = RequestMethod.POST)
    public @ResponseBody
    NetState shareRegister(HttpServletRequest request, String Mobile, String UserName, String ShareId,
                           String NewPassword, String InviteCode, String ParentId,
                           String WXOpenId, String WXName, String WXPic, String SMSCode, String AppleUserId)
            throws Exception {
        String Password = null;
        if (NewPassword != null && !NewPassword.equals("")) {
            Password = NewPassword;
        } else if (Password == null & ShareId != null && !ShareId.equals("")) {
            Password = Mobile;
        }

        // 返回数据对象
        NetState netState = new NetState();        //返回数据类型
        // 验证参数
        if (Mobile == null || Mobile.equals("")) {        //判断
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            Boolean isMobile = Produce.isMobile(Mobile);
            if (isMobile == false) {                        //判断
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请填写正确手机号");
                return netState;
            }
            if (SMSCode != null && !SMSCode.equals("")) {
                List<Smsinfoes> smsinfoes = smsinfoesService.selectByAgentIDAndMobile(ParentId, Mobile);
                if (smsinfoes != null && smsinfoes.size() > 0) {
                    if (smsinfoes.get(0).getNum().equals(Integer.parseInt(SMSCode))) {

                    } else {
                        netState.setErrorCode(NetState.ERROR_OPERATE);
                        netState.setData("验证码错误");
                    }
                } else {
                    netState.setErrorCode(NetState.NODATA);
                    netState.setData("验证码不存在");
                }
            }
            // 判断邀请码
            if (InviteCode != null && !InviteCode.equals("")) {
                Boolean result = Produce.isMobile(InviteCode);
                if (result) {
                    List<Subscribers> findUser = subscribersService.selectBySub(InviteCode, ParentId);
                    if (findUser != null && findUser.size() > 0) {
                        ShareId = findUser.get(0).getId();
                    } else {
                        netState.setErrorCode(NetState.PARAMS_ERROR);
                        netState.setData("用户不存在");
                        return netState;
                    }
                } else {
                    List<InviteCode> code = inviteCodeService.selectByCode(InviteCode);
                    if (code != null && code.size() > 0) {
                        ShareId = code.get(0).getUserid();
                    } else {
                        netState.setErrorCode(NetState.PARAMS_ERROR);
                        netState.setData("邀请码错误");
                        return netState;
                    }
                }
            }

            // 分享者信息
            Subscribers shareUser = subscribersService.selectByPrimaryKey(ShareId);

            // 标签id
            String tabId = null;
            if (shareUser.getTabid() != null && !shareUser.getTabid().equals("")) {
                tabId = shareUser.getTabid();
            } else {
                tabId = shareUser.getId();
            }

            if (shareUser == null) {
                netState.setErrorCode(NetState.NODATA);
                netState.setData("未查询到分享者信息,请联系客服");
                return netState;
            }

            List<Subscribers> subscribers = subscribersService.selectBySub(Mobile, shareUser.getParentid());
            if (subscribers != null && subscribers.size() > 0) {
                netState.setErrorCode(NetState.DATA_RE);
                netState.setData("该手机号已注册");
            } else {
                List<Users> agents = usersService.selectByPid(shareUser.getParentid());
                if (agents == null || agents.size() == 0) {
                    netState.setErrorCode(NetState.ACCOUNT_ERROR);
                    netState.setData("该代理不存在");
                } else {
                    Users agent = agents.get(0);
                    int mon = 0; // 注册用户话费
                    int shopmon = 0; // 注册用户购物金
                    // 分享注册赠送 app自定义的注册赠送话费金额和分享注册赠送话费金额
                    if (agent.getBlance().intValue() >= agent.getRegimoney()) {
                        mon = agent.getRegimoney();
                    }
                    // 被分享者 赠送
                    if (agent.getBlance().intValue() >= agent.getRegimoney() + agent.getCallparshare()) {
                        mon = agent.getRegimoney() + agent.getCallparshare();
                    } else {
                        mon = 0;
                    }
                    // 分享注册赠送 分享注册赠送购物券金额
//                    Integer shopblance = agent.getShopblance();
//                    if (shopblance != null) {
//                        if (shopblance >= agent.getRegishopmoney()) {
//                            shopmon = agent.getRegishopmoney();
//                        }
//                        // 被分享者 赠送
//                        if (shopblance >= agent.getRegishopmoney() + agent.getShopparshare()) {
//                            shopmon = agent.getRegishopmoney() + agent.getShopparshare();
//                        } else {
//                            shopmon = 0;
//                        }
//                    }

//					System.out.println("充值赠送购物余额:" + Money);
                    // VOS创建用户
                    if (VosHelper.Register(agent.getAgentprefix() + Mobile, agent.getUsername(),
                            Produce.plusDay(agent.getRegitime(), Produce.getNowDate()).getTime() + "", mon + "",
                            agent.getFreeroute())) {
                        // 新用户id
                        String newid = Produce.getUUID();
                        // 创建用户
                        Subscribers record = new Subscribers(newid, PasswordUtils.toPWD(Password),
                                Produce.getNowDate(), Produce.getNowDate(), IP.getIpAddr(request), 4, true,
                                Mobile, shareUser.getParentid(), Produce.plusDay(agent.getRegitime(), Produce.getNowDate()),
                                "/Images/logo.png", 7, shareUser.getShopid(), "1", null, null, false, shopmon,
                                new SimpleDateFormat("yyyy-MM-dd")
                                        .format(Produce.plusDay(agent.getRegitime(), Produce.getNowDate())),
                                null, "0", null, null, UserName, ShareId, false, false,
                                false, tabId);
                        record.setWxopenid(WXOpenId);
                        record.setWxname(WXName);
                        record.setWxpic(WXPic);
                        record.setAppleuserid(AppleUserId);
//						record.setQqname(QQOpenId);
//						record.setQqname(QQName);
//						record.setQqpic(QQPic);
                        int result = subscribersService.insertSelective(record);

                        // TODO 保存shared_id-->shareUser.getID
                        int num = Integer.parseInt(Mobile.substring(0, 7));
                        AttributionsExample attributionsExample = new AttributionsExample();
                        attributionsExample.getOredCriteria()
                                .add(attributionsExample.createCriteria().andSectionnoEqualTo(num));
                        List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                        String address = null;
                        if (attributions == null || attributions.size() == 0) {
                            address = "未知归属地";
                        } else {
                            address = attributions.get(0).getCity();
                        }
                        if (result > 0) {
                            // TODO 整改IP获取的address，
                            int resultR = registerinfoesService.insert(Mobile, IP.getIpAddr(request), address,
                                    shareUser.getParentid(), address, true);
                            if (resultR > 0) {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("注册成功");
                                netState.setOtherJson(newid);
                            } else {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("注册成功,但是在获取存储您的信息时候出现了一些问题");
                                netState.setOtherJson(newid);
                            }

                            try {
                                // 注册者变更记录
                                changeRecordService.insertSelective(new ChangeRecord(shareUser.getParentid(), shareUser.getShopid(), newid,
                                        Produce.getNowDate(), new BigDecimal(0), BigDecimal.valueOf(mon),
                                        1, null, Produce.plusDay(agent.getRegitime(), Produce.getNowDate()), "分享注册", new BigDecimal(0),
                                        BigDecimal.valueOf(shopmon), 1, null, Produce.plusDay(agent.getRegitime(), Produce.getNowDate()), "分享注册", null));
                            } catch (Exception e) {
                                logsService.insert(CommContent.TYPE_CREATE, Mobile + "注册余额变更记录异常", agent.getUsername(), true,
                                        IP.getIpAddr(request));
                            }

                            // 用户注册成功 分享者返利
                            Integer sharemon = 0; // 分享用户话费
                            Integer shareshopmon = 0; // 分享用户购物金

                            // 查询分享者 变更前话费余额
                            BigDecimal shareBeforeB = new BigDecimal(0);
                            //备注
                            String shareRemark = null;
                            try {
                                // TODO 暂时配注
                                String shareUserR = VosHelper
                                        .GetVosAccount("{accounts:['" + agent.getAgentprefix() + shareUser.getMobile() + "']}");
                                if (shareUserR != null) {
                                    VosModelList shareUserR1 = GsonUtil.getObject(shareUserR, VosModelList.class);
                                    if (shareUserR1.retCode == 0) {
                                        shareBeforeB = shareUserR1.infoCustomers[0].getMoney();
                                    } else {
                                        shareBeforeB = new BigDecimal(0);
                                        shareRemark = "暂无记录";
                                    }
                                }
                            } catch (Exception e) {
                                shareBeforeB = new BigDecimal(0);
                                shareRemark = "暂无记录";
                            }
                            //查询分享者 变更前话费有效期
                            Date shareBeforeTimeB = shareUser.getEndtime();
                            //查询分享者 变更话费有效期
                            Date shareChangeTimeB = new Date();
                            // 查询分享者 变更前购物金余额
                            BigDecimal shareBeforeS = BigDecimal.valueOf(shareUser.getShopBalance());
                            // 查询分享者 变更前购物金有效期
                            Date shareBeforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
                                    .parse(shareUser.getShopEnddate());

                            // 分享返利赠送 分享返利话费金额
                            if (agent.getBlance().intValue() >= agent.getCallmeshare()) {
                                sharemon = agent.getCallmeshare();
                            } else {
                                sharemon = 0;
                            }
                            // 分享返利赠送 分享返利金额购物券金额
                            if (agent.getShopblance().intValue() >= agent.getShopmeshare()) {
                                shareshopmon = agent.getShopmeshare();
                            } else {
                                shareshopmon = 0;
                            }
                            String sharepayinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
                                    + shareUser.getMobile() + "\",\"ownerType\":\"2\",\"money\":\"" + sharemon
                                    + "\",\"memo\":\"" + agent.getUsername() + "，分享赠送" + sharemon + "元\"}");
                            VosModelList v1 = GsonUtil.getObject(sharepayinfo, VosModelList.class);
                            // TODO if(是否设置了二级分销){找到shareUser.getShared_id这个用户，给其进行充值（判断充值金额）}
                            if (v1 != null && v1.retCode == 0) {
                                if (agent.getId().equals("478f572854384205972fae478a81948c")) {
                                    String shareinfo = VosHelper.ModifyVosAccount("{\"account\":\"" + agent.getAgentprefix()
                                            + shareUser.getMobile() + "\",\"feeRateGroup\":\"" + agent.getFreeroute()
                                            + "\",\"agentAccount\":\"" + agent.getUsername() + "\",\"validTime\":\""
                                            + Produce.plusDay(1, shareUser.getEndtime()).getTime() + "\"}");
                                    VosModelList v12 = GsonUtil.getObject(shareinfo, VosModelList.class);
                                    if (v12 != null && v12.retCode == 0) {
                                        shareUser.setEndtime(Produce.plusDay(1, shareUser.getEndtime()));
                                        shareChangeTimeB = Produce.plusDay(1, shareUser.getEndtime());
                                    }
                                } else {
                                    shareChangeTimeB = shareBeforeTimeB;
                                }

                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setOtherJson(newid);
                            } else {
                                // 分享返利赠送失败 返回-1
                                sharemon = -1;
                            }
                            shareUser.setShopBalance(shareUser.getShopBalance() + shareshopmon);
                            int shareR = subscribersService.updateByPrimaryKeySelective(shareUser);
                            if (shareR > 0) {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setOtherJson(newid);
//							   netState.setData("注册成功,分享者购物券赠送成功");
                            } else {
                                // 分享返利赠送失败 返回-1
                                shareshopmon = -1;
                            }
                            // 一级分享者
                            rewardsService.insert(
                                    new Rewards(1, agent.getId(), shareUser.getId(), newid, new BigDecimal(sharemon),
                                            new BigDecimal(shareshopmon), 0.0, 1, Produce.getNowDate()));

                            try {
                                // 一级分享者变更记录
                                changeRecordService.insertSelective(new ChangeRecord(shareUser.getParentid(), shareUser.getShopid(),
                                        shareUser.getId(), Produce.getNowDate(), shareBeforeB,
                                        BigDecimal.valueOf(sharemon), 1, shareBeforeTimeB, shareChangeTimeB, "一级分享返利", shareBeforeS,
                                        BigDecimal.valueOf(shareshopmon), 1, shareBeforeTimeS, shareBeforeTimeS, "一级分享返利", shareRemark));
                            } catch (Exception e) {
                                logsService.insert(CommContent.TYPE_CREATE, shareUser.getMobile() + "一级分享返利余额变更记录异常", agent.getUsername(), true,
                                        IP.getIpAddr(request));
                            }

                            //查询分享者是否有分享红包
                            List<ShareRedPacket> shareRedPackets = shareRedPacketService.selectByStatus(shareUser.getId());
                            if (shareRedPackets != null && shareRedPackets.size() > 0) {
                                //有红包 给注册者红包
                                ShareRedPacket shareRedPacket = shareRedPackets.get(0);
                                //查询已经拆分好了的 红包
                                List<ShareRedPacketMoney> shareRedPacketMonies = shareRedPacketMoneyService.selectByRedPacketId(shareUser.getId(),
                                        shareRedPacket.getId());
                                //获取第一个红包金额
                                ShareRedPacketMoney shareRedPacketMoney = shareRedPacketMonies.get(0);

                                String redPacketPayinfo = VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
                                        + Mobile + "\",\"ownerType\":\"2\",\"money\":\"" + shareRedPacketMoney.getMoney()
                                        + "\",\"memo\":\"" + agent.getUsername() + "，红包赠送" + shareRedPacketMoney.getMoney() + "元\"}");
                                VosModelList v4 = GsonUtil.getObject(redPacketPayinfo, VosModelList.class);

                                if (v4 != null && v4.retCode == 0) {
                                    //红包到账成功 更新剩余红包金额
                                    shareRedPacket.setMoney(shareRedPacket.getMoney().subtract(shareRedPacketMoney.getMoney()));
                                    shareRedPacket.setNumber(shareRedPacket.getNumber() - 1);
                                    if (shareRedPacket.getNumber() - 1 == 0) {
                                        shareRedPacket.setStatus((byte) 0);
                                    }
                                    shareRedPacketService.updateByPrimaryKeySelective(shareRedPacket);

                                    try {
                                        // 注册者领取红包变更记录
                                        changeRecordService.insertSelective(new ChangeRecord(shareUser.getParentid(), shareUser.getShopid(), newid,
                                                Produce.getNowDate(), BigDecimal.valueOf(mon), shareRedPacketMoney.getMoney(),
                                                1, null, Produce.plusDay(agent.getRegitime(), Produce.getNowDate()), "领取红包", BigDecimal.valueOf(shopmon),
                                                new BigDecimal(0), 1, null, Produce.plusDay(agent.getRegitime(), Produce.getNowDate()), "领取红包", null));
                                    } catch (Exception e) {
                                        logsService.insert(CommContent.TYPE_CREATE, Mobile + "注册领取红包余额变更记录异常", agent.getUsername(), true,
                                                IP.getIpAddr(request));
                                    }

                                    //更新已拆分好红包使用状态
                                    shareRedPacketMoney.setStatus((byte) 1);
                                    shareRedPacketMoneyService.updateByPrimaryKeySelective(shareRedPacketMoney);
                                    // 插入一条领取记录
                                    shareRedPacketLogService.insertSelective(new ShareRedPacketLog(Produce.getUUID(),
                                            shareRedPacket.getId(), Produce.getNowDate(), new BigDecimal(0), newid,
                                            (byte) 1));

                                    netState.setErrorCode(NetState.SUCCESS_CONN);
                                    netState.setOtherJson(newid);
                                }
                            }

                            // 分享者 的上级分享者 获取返利
                            if (shareUser.getShareper() != null && !shareUser.getShareper().equals("")) {
                                Subscribers shareperUser = subscribersService
                                        .selectByPrimaryKey(shareUser.getShareper());
                                if (shareperUser != null) {
                                    // 用户注册成功 分享者上级分享者返利
                                    Integer sharepermon = 0; // 分享用户话费
                                    Integer shareshoppermon = 0; // 分享用户购物金

                                    // 查询二级分享者 变更前话费余额
                                    BigDecimal shareperBeforeB = new BigDecimal(0);
                                    //备注
                                    String shareperRemark = null;
                                    try {
                                        // TODO 暂时配注
                                        String shareUserR = VosHelper
                                                .GetVosAccount("{accounts:['" + agent.getAgentprefix() + shareperUser.getMobile() + "']}");
                                        if (shareUserR != null) {
                                            VosModelList shareUserR1 = GsonUtil.getObject(shareUserR, VosModelList.class);
                                            if (shareUserR1.retCode == 0) {
                                                shareperBeforeB = shareUserR1.infoCustomers[0].getMoney();
                                            } else {
                                                shareperBeforeB = new BigDecimal(0);
                                                shareperRemark = "暂无记录";
                                            }
                                        }
                                    } catch (Exception e) {
                                        shareperBeforeB = new BigDecimal(0);
                                        shareperRemark = "暂无记录";
                                    }
                                    //查询二级分享者 变更话费有效期
                                    Date shareperChangeTimeB = new Date();
                                    //查询二级分享者 变更前话费有效期
                                    Date shareperBeforeTimeB = shareperUser.getEndtime();
                                    // 查询二级分享者 变更前购物金余额
                                    BigDecimal shareperBeforeS = BigDecimal.valueOf(shareperUser.getShopBalance());
                                    // 查询二级分享者 变更前购物金有效期
                                    Date shareperBeforeTimeS = new SimpleDateFormat("yyyy-MM-dd")
                                            .parse(shareperUser.getShopEnddate());

                                    // 分享返利赠送 分享返利话费金额 为分享者上级分享者 二级分享者
                                    if (agent.getBlance().intValue() >= agent.getCallshareper()) {
                                        sharepermon = agent.getCallshareper();
                                    } else {
                                        sharepermon = 0;
                                    }
                                    // 分享返利赠送 分享返利金额购物券金额 为分享者上级分享者 二级分享者
                                    if (agent.getShopblance().intValue() >= agent.getShopshareper()) {
                                        shareshoppermon = agent.getShopshareper();
                                    } else {
                                        shareshoppermon = 0;
                                    }
                                    String shareperpayinfo = VosHelper.PayVosAccount("{\"ownerName\":\""
                                            + agent.getAgentprefix() + shareperUser.getMobile()
                                            + "\",\"ownerType\":\"2\",\"money\":\"" + sharepermon + "\",\"memo\":\""
                                            + agent.getUsername() + "，分享赠送" + sharepermon + "元\"}");
                                    VosModelList v2 = GsonUtil.getObject(shareperpayinfo, VosModelList.class);
                                    // TODO if(是否设置了二级分销){找到shareUser.getShared_id这个用户，给其进行充值（判断充值金额）}
                                    if (v2 != null && v2.retCode == 0) {
                                        if (agent.getId().equals("478f572854384205972fae478a81948c")) {
                                            String shareperinfo = VosHelper.ModifyVosAccount("{\"account\":\"" + agent.getAgentprefix()
                                                    + shareperUser.getMobile() + "\",\"feeRateGroup\":\"" + agent.getFreeroute()
                                                    + "\",\"agentAccount\":\"" + agent.getUsername() + "\",\"validTime\":\""
                                                    + Produce.plusDay(1, shareperUser.getEndtime()).getTime() + "\"}");
                                            VosModelList v22 = GsonUtil.getObject(shareperinfo, VosModelList.class);
                                            if (v22 != null && v22.retCode == 0) {
                                                shareUser.setEndtime(Produce.plusDay(1, shareperUser.getEndtime()));
                                                shareperChangeTimeB = Produce.plusDay(1, shareperUser.getEndtime());
                                            }
                                        } else {
                                            shareperChangeTimeB = shareperBeforeTimeB;
                                        }

                                        netState.setErrorCode(NetState.SUCCESS_CONN);
                                        netState.setOtherJson(newid);
                                    } else {
                                        // 分享返利赠送失败 返回-1
                                        sharepermon = -1;
                                    }
                                    shareperUser.setShopBalance(shareperUser.getShopBalance() + shareshoppermon);
                                    int shareperR = subscribersService.updateByPrimaryKeySelective(shareperUser);
                                    if (shareperR > 0) {
                                        netState.setErrorCode(NetState.SUCCESS_CONN);
                                        netState.setOtherJson(newid);
//										netState.setData("注册成功,分享者上级分享者购物券赠送成功");
                                    } else {
                                        // 分享返利赠送失败 返回-1
                                        shareshoppermon = -1;
                                    }
                                    // 上级分享者 就是二级分享者
                                    rewardsService.insert(new Rewards(1, agent.getId(), shareperUser.getId(), newid,
                                            new BigDecimal(sharepermon), new BigDecimal(shareshoppermon), 0.0, 2,
                                            Produce.getNowDate()));

                                    try {
                                        // 二级分享者变更记录
                                        changeRecordService.insertSelective(new ChangeRecord(shareperUser.getParentid(), shareperUser.getShopid(),
                                                shareperUser.getId(), Produce.getNowDate(), shareperBeforeB,
                                                BigDecimal.valueOf(sharepermon), 1, shareperBeforeTimeB, shareperChangeTimeB, "二级分享返利",
                                                shareperBeforeS, BigDecimal.valueOf(shareshoppermon), 1, shareperBeforeTimeS,
                                                shareperBeforeTimeS, "二级分享返利", shareperRemark));
                                    } catch (Exception e) {
                                        logsService.insert(CommContent.TYPE_CREATE, shareperUser.getMobile() + "二级分享返利余额变更记录异常", agent.getUsername(), true,
                                                IP.getIpAddr(request));
                                    }

                                    if (shareperUser.getShareper() != null && !shareperUser.getShareper().equals("")) {
                                        Subscribers proUser = subscribersService
                                                .selectByPrimaryKey(shareperUser.getShareper());
                                        int level = 3;
                                        if (proUser.getParentid().equals("d093179851af43dfbb1bc6639334b109")) {
                                            for (int i = 0; i < 100; i++) {
                                                rewardsService.insert(new Rewards(1, agent.getId(), proUser.getId(), newid,
                                                        new BigDecimal(0), new BigDecimal(0), 0.0, level,
                                                        Produce.getNowDate()));
                                                if (proUser.getShareper() != null && !proUser.getShareper().equals("")) {
                                                    proUser = subscribersService.selectByPrimaryKey(proUser.getShareper());
                                                    level++;
                                                } else {
                                                    break;
                                                }
                                            }
                                        } else {
                                            rewardsService.insert(new Rewards(1, agent.getId(), proUser.getId(), newid,
                                                    new BigDecimal(0), new BigDecimal(0), 0.0, level,
                                                    Produce.getNowDate()));
                                        }
                                    }
                                } else {
                                    netState.setErrorCode(NetState.SUCCESS_CONN);
                                    netState.setData("注册成功,但是未查询到分享者上级分享者信息,请联系客服");
                                    netState.setOtherJson(newid);
                                }
                            }
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("注册失败");
                        }
                    } else {
                        netState.setErrorCode(NetState.SYSTEM_ERROR);
                        netState.setData("注册失败");
                    }
                }
            }
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "分享注册");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(Mobile, ShareId),
//                GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 注册信息
    @CrossOrigin
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public @ResponseBody
    NetState register(HttpServletRequest request, String Mobile, String ParentId, String Password,
                      String UserName, String registration_id, String AppleUserId,
                      String WXOpenId, String WXName, String WXPic) throws Exception {
        log.warn("[API][/register] Mobile={},ParentId={},Password={},UserName={},registration_id={},AppleUserId={},WXOpenId={},WXName={},WXPic={}", Mobile, ParentId, Password, UserName, registration_id, AppleUserId, WXOpenId, WXName, WXPic);
//        if (redisCacheManager.hasKey("register:" + Mobile)) {
//            return new NetState(NetState.FEAILED, "请勿重复提交");
//        }
        // 返回数据对象
        NetState netState = new NetState();
        if (StringUtils.isEmpty(Password)) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("密码不能为空");
            return netState;
        }
        String pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$";
        if (!Pattern.compile(pattern).matcher(Password).matches()){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("密码必须包含大小写字母和数字，并且最少8位");
            return netState;
        }
        // 验证参数
        if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            Boolean isMobile = Produce.isMobile(Mobile);
            if (isMobile == false) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("请填写正确手机号");
                return netState;
            }
            if (null == OrionUtil.getUserInfo(Mobile)){
                OrionUtil.registUser(Mobile,Password);
            }
            // 判断微信OpenId是否绑定
            if (WXOpenId != null && !WXOpenId.equals("")) {
                List<Subscribers> wxSubscribers = subscribersService.selectByWxOpenId(WXOpenId, ParentId);
                if (wxSubscribers != null && wxSubscribers.size() > 0) {
                    netState.setData("该微信已被绑定");
                    netState.setErrorCode(NetState.WX_OPENID_REPEAT);
                    return netState;
                }
            }
            // 判断苹果UserId是否绑定
            if (AppleUserId != null && !AppleUserId.equals("")) {
                List<Subscribers> appleSubscribers = subscribersService.selectByAppleUserId(AppleUserId, ParentId);
                if (appleSubscribers != null && appleSubscribers.size() > 0) {
                    netState.setData("该微信已被绑定");
                    netState.setErrorCode(NetState.APPLE_USERID_REPEAT);
                    return netState;
                }
            }
            List<Subscribers> subscribers = subscribersService.selectBySub(Mobile, ParentId);
            if (subscribers != null && subscribers.size() > 0) {
                netState.setErrorCode(NetState.DATA_RE);
                netState.setData("该账号已注册，如果您忘记密码，请在登录页点击忘记密码");
            } else {
                List<Users> agents = usersService.selectByPid(ParentId);
                if (agents == null || agents.size() == 0) {
                    netState.setErrorCode(NetState.ACCOUNT_ERROR);
                    netState.setData("该代理不存在");
                } else {
//                    synchronized (obj) {
//                        if (redisCacheManager.hasKey("register:" + Mobile)) {
//                            return new NetState(NetState.FEAILED, "请勿重复提交");
//                        }
//                        redisCacheManager.set("register:" + Mobile, ParentId, 60);
//                    }


                    Users agent = agents.get(0);
                    Integer mon = 0;
                    Integer shopmon = 0;
                    if (agent.getBlance().intValue() >= agent.getRegimoney()) {
                        mon = agent.getRegimoney();
                    } else {
                        mon = 0;
                    }
                    // TODO 注意：这不是改BUG的人写的代码！
                    // 已知错误：agent.getRegishopmoney()参数为空 此字段为注册赠送购物金额
                    // so 最好的办法当然是得从根源改
                    // 数据库应该设计非空默认为0 但是前开发人员用Mybatis时调的是insert接口，不是insertSelective接口
                    // 因为insert是添加所有字段信息，这个字段为空sql就出错了，要是用insertSelective字段为空的话就是添加默认值0
                    // 导致目前数据库为不是非空，然后就没有默认值了，so 数据库字段为null，所以下面的判断就出错了
                    // 懒得改了 用try捕捉一下异常算了
                    // 有时间的可以改改 具体工程量未知
                    // PS:之前写的挺烂的
                    try {
                        if (agent.getShopblance().intValue() >= agent.getRegishopmoney()) {
                            shopmon = agent.getRegishopmoney();
                        } else {
                            shopmon = 0;
                        }
                    } catch (NullPointerException e) {
                        System.out.println("其实有错误：LoginController.java:577");
                        shopmon = 0;
                    }
                    // VOS创建用户
                    if (VosHelper.Register(agent.getAgentprefix() + Mobile, agent.getUsername(),
                            Produce.plusDay(agent.getRegitime(), Produce.getNowDate()).getTime() + "", mon + "",
                            agent.getFreeroute())) {
                        // 创建用户
                        Subscribers record = new Subscribers(Produce.getUUID(), PasswordUtils.toPWD(Password), Produce.getNowDate(),
                                Produce.getNowDate(), IP.getIpAddr(request), 4, true, Mobile, ParentId,
                                Produce.plusDay(agent.getRegitime(), Produce.getNowDate()), "/Images/logo.png", 7,
                                agents.get(0).getId(), "1", null, null, false, shopmon,
                                new SimpleDateFormat("yyyy-MM-dd")
                                        .format(Produce.plusDay(agent.getRegitime(), Produce.getNowDate())),
                                null, "0", null, null, UserName, false,
                                false, false, Produce.plusDay(30, Produce.getNowDate()));
                        record.setWxopenid(WXOpenId);
                        record.setWxname(WXName);
                        record.setWxpic(WXPic);
//						record.setQqname(QQOpenId);
//						record.setQqname(QQName);
//						record.setQqpic(QQPic);
                        int result = subscribersService.insertSelective(record);
                        int num = Integer.parseInt(Mobile.substring(0, 7));
                        AttributionsExample attributionsExample = new AttributionsExample();
                        attributionsExample.getOredCriteria()
                                .add(attributionsExample.createCriteria().andSectionnoEqualTo(num));
                        List<Attributions> attributions = attributionsService.selectByExample(attributionsExample);
                        String address = null;
                        if (attributions == null || attributions.size() == 0) {
                            address = "未知归属地";
                        } else {
                            address = attributions.get(0).getCity();
                        }
                        if (result > 0) {
                            // TODO 整改IP获取的address，
                            int resultR = registerinfoesService.insert(Mobile, IP.getIpAddr(request), address, ParentId,
                                    address, true);
                            if (resultR > 0) {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("注册成功");
                            } else {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("注册成功,但是在获取存储您的信息时候出现了一些问题");
                            }

                            // 注册者变更记录
                            List<Subscribers> newSubList = subscribersService.selectBySub(Mobile, ParentId);
                            if (newSubList != null && newSubList.size() > 0) {
                                Subscribers newSub = newSubList.get(0);
                                try {
                                    changeRecordService.insertSelective(new ChangeRecord(ParentId, agents.get(0).getId(),
                                            newSub.getId(), Produce.getNowDate(), new BigDecimal(0),
                                            BigDecimal.valueOf(mon), 1, null, Produce.plusDay(agent.getRegitime(), Produce.getNowDate()), "注册",
                                            new BigDecimal(0), BigDecimal.valueOf(shopmon), 1, null, Produce.plusDay(agent.getRegitime(),
                                            Produce.getNowDate()), "注册", null));
                                } catch (Exception e) {
                                    logsService.insert(CommContent.TYPE_CREATE, Mobile + "注册余额变更记录异常", agent.getUsername(), true,
                                            IP.getIpAddr(request));
                                }
                            }

                            if (agent.getIsregisterpush() == 1) {
//                                if (registration_id != null) {
//                                    JPushUtil.setPush("手机号" + Mobile + "用户注册成功", registration_id, agent);
//                                }
                            }
                        } else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("注册失败");
                        }
                    } else {
                        netState.setErrorCode(NetState.SYSTEM_ERROR);
                        netState.setData("系统繁忙,注册失败");
                    }
                }
            }
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "注册");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(Mobile, ParentId),
//                GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 登录（填写密码）
    @CrossOrigin
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody
    NetState login(HttpServletRequest request, String Mobile, String ParentId, String Password,
                   String WXOpenId, String QQOpenId, String AppleUserId, String SMSCode) {
        // 返回数据对象
        NetState netState = new NetState();
        // 验证参数
        if (Mobile == null && ParentId == null && WXOpenId == null) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            if (Password == null && Password.equals("")) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("您输入的密码为空");
                return netState;
            }
            List<Subscribers> subscribers = null;
            if (WXOpenId != null && !WXOpenId.equals("")) {
                subscribers = subscribersService.selectByWxOpenId(WXOpenId, ParentId);
                if (subscribers != null && subscribers.size() > 0) {
                    Subscribers s = subscribers.get(0);
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setData("登陆成功");
                    s.setPassword(null);
                    netState.setJson(s);
                } else {
                    netState.setErrorCode(NetState.ACCOUNT_ERROR);
                    netState.setData("该用户不存在");
                }
            } else if (QQOpenId != null && !QQOpenId.equals("")) {
//				subscribers = subscribersService.selectByQQOpenId(QQOpenId);
//				if (subscribers != null && subscribers.size() > 0) {
//					Subscribers s = subscribers.get(0);
//					netState.setErrorCode(NetState.SUCCESS_CONN);
//					netState.setData("登陆成功");
//					s.setPassword(null);
//					netState.setJson(s);
//				} else {
//					netState.setErrorCode(NetState.ACCOUNT_ERROR);
//					netState.setData("该用户不存在");
//				}
            } else if (AppleUserId != null && !AppleUserId.equals("")) {
                subscribers = subscribersService.selectByAppleUserId(AppleUserId, ParentId);
                if (subscribers != null && subscribers.size() > 0) {
                    Subscribers s = subscribers.get(0);
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setData("登陆成功");
                    s.setPassword(null);
                    netState.setJson(s);
                } else {
                    netState.setErrorCode(NetState.ACCOUNT_ERROR);
                    netState.setData("该用户不存在");
                }
            } else {
                subscribers = subscribersService.selectBySub(Mobile, ParentId);
                if (null == subscribers  || subscribers.isEmpty()) {
                    if (OrionUtil.login(Mobile,Password)){
                        try {
                            register(request, Mobile, ParentId, Password, Mobile, null, null, null, null, null);
                        } catch (Exception e) {
                            log.error("登录注册失败");
                        }
                        subscribers = subscribersService.selectBySub(Mobile, ParentId);
                    }else {
                        netState.setErrorCode(NetState.ACCOUNT_ERROR);
                        netState.setData("该用户不存在");
                        return netState;
                    }
                }
                    Subscribers s = subscribers.get(0);
                    if (SMSCode != null && !SMSCode.equals("")) {
                        List<Smsinfoes> smsinfoes = smsinfoesService.selectByAgentIDAndMobile(ParentId, Mobile);
                        if (smsinfoes != null && smsinfoes.size() > 0) {
                            if (smsinfoes.get(0).getNum().equals(Integer.parseInt(SMSCode))) {
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("登陆成功");
                                s.setPassword(null);
                                netState.setJson(s);
                            } else {
                                netState.setErrorCode(NetState.ERROR_OPERATE);
                                netState.setData("验证码错误");
                            }
                        } else {
                            netState.setErrorCode(NetState.NODATA);
                            netState.setData("验证码不存在");
                        }
                    } else {
                        if (PasswordUtils.decodePWD(Password, s.getPassword())) {
                            netState.setErrorCode(NetState.SUCCESS_CONN);
                            netState.setData("登陆成功");
                            s.setPassword(null);
                            netState.setJson(s);
                        } else {
                            netState.setErrorCode(NetState.PARAMS_ERROR);
                            netState.setData("密码错误");
                        }
                    }
            }
        }
        if (null == OrionUtil.getUserInfo(Mobile)){
            OrionUtil.registUser(Mobile,Password);
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "登录");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
//                Produce.parmsToString(Mobile, ParentId, Password), GsonUtil.createJsonString(netState)));
        return netState;
    }

    public static void main(String[] args) {
        System.out.println(PasswordUtils.toPWD("123456"));
    }

    // 微信端 登录（填写密码）

    @RequestMapping(value = "/wxLogin", method = RequestMethod.POST)
    public @ResponseBody
    NetState testlogin(HttpServletRequest request, HttpServletResponse response, String Mobile,
                       String ParentId, String Password) {
        // 微信端 跨域请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 返回数据对象
        NetState netState = new NetState();
        // 验证参数
        if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("您输入的参数不正确");
        } else {
            SubscribersExample subscribersExample = new SubscribersExample();
            subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(Mobile)
                    .andParentidEqualTo(ParentId).andDatastatusEqualTo(true));
            List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
            if (subscribers != null && subscribers.size() > 0) {
                Subscribers s = subscribers.get(0);
                if (PasswordUtils.decodePWD(Password, s.getPassword())) {
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setData("登陆成功");
                    s.setPassword(null);
                    netState.setJson(s);
                } else {
                    netState.setErrorCode(NetState.PARAMS_ERROR);
                    netState.setData("密码错误");
                }
            } else {
                netState.setErrorCode(NetState.ACCOUNT_ERROR);
                netState.setData("该用户不存在");
            }
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "登录");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
//                Produce.parmsToString(Mobile, ParentId, Password), GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 修改密码
    @CrossOrigin
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    public @ResponseBody
    NetState updatePwd(HttpServletRequest request, HttpServletResponse response, String Theme) {
        NetState netState = new NetState();
        String AuthorizationToken = request.getHeader("SDB-Authorization");
        AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
        if (acessToken == null || acessToken.equals("")) {
            netState.setData("数据签名错误");
            netState.setErrorCode(NetState.SIGN_ERROR);
        } else {
            if (Theme == null && Theme.equals("")) {
                netState.setErrorCode(NetState.PARAMS_ERROR);
                netState.setData("您输入的密码为空");
                return netState;
            }
            String Mobile = acessToken.getMobile();
            String ParentId = acessToken.getParentid();

            SubscribersExample subscribersExample = new SubscribersExample();
            subscribersExample.getOredCriteria()
                    .add(subscribersExample.createCriteria().andParentidEqualTo(ParentId).andMobileEqualTo(Mobile));
            List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
            if (subscribers != null && subscribers.size() == 1) {
                Subscribers user = subscribers.get(0);
                user.setPassword(PasswordUtils.toPWD(Theme));
                int re = subscribersService.updateByPrimaryKeySelective(user);
                if (re == 1) {
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setData("修改成功");
                } else {
                    netState.setErrorCode(NetState.SYSTEM_ERROR);
                    netState.setData("修改失败");
                }
            } else {
                netState.setErrorCode(NetState.ACCOUNT_ERROR);
                netState.setData("修改失败，该用户不存在");
            }
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "修改密码");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
//                AuthorizationToken + Produce.parmsToString(Theme), GsonUtil.createJsonString(netState)));
        return netState;
    }

    // 修改密码
    @RequestMapping(value = "/wxUpdatePwd", method = RequestMethod.POST)
    public @ResponseBody
    NetState wxUpdatePwd(HttpServletRequest request, HttpServletResponse response,
                         String Theme) {
        // 微信端 跨域请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 返回数据对象
        NetState netState = new NetState();
        String AuthorizationToken = request.getHeader("Authorization");
        AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
        if (acessToken == null || acessToken.equals("")) {
            netState.setData("数据签名错误");
            netState.setErrorCode(NetState.SIGN_ERROR);
        } else {
            String Mobile = acessToken.getMobile();
            String ParentId = acessToken.getParentid();

            SubscribersExample subscribersExample = new SubscribersExample();
            subscribersExample.getOredCriteria()
                    .add(subscribersExample.createCriteria().andParentidEqualTo(ParentId).andMobileEqualTo(Mobile));
            List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
            if (subscribers != null && subscribers.size() == 1) {
                Subscribers user = subscribers.get(0);
                user.setPassword(PasswordUtils.toPWD(Theme));
                int re = subscribersService.updateByPrimaryKeySelective(user);
                if (re == 1) {
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setData("修改成功");
                } else {
                    netState.setErrorCode(NetState.SYSTEM_ERROR);
                    netState.setData("修改失败");
                }
            } else {
                netState.setErrorCode(NetState.ACCOUNT_ERROR);
                netState.setData("修改失败，该用户不存在");
            }
        }
//        Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "修改密码");
//        apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
//                AuthorizationToken + Produce.parmsToString(Theme), GsonUtil.createJsonString(netState)));
        return netState;
    }

    @RequestMapping(value = "/share", method = RequestMethod.POST)
    public @ResponseBody
    NetState share(HttpServletRequest request, String mobile, String userName, String shareId) throws Exception {
        NetState netState = new NetState();

        String newId = null;

        List<Subscribers> subscribersList = subscribersService.selectBySharePerJSJ(shareId);
        if (subscribersList != null && subscribersList.size() > 0) {
            int x = (int) (Math.random() * subscribersList.size());
            newId = subscribersList.get(x).getId();
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setData("注册成功");
        } else {
            Subscribers sub = subscribersService.selectByPrimaryKey(shareId);

            netState = this.shareRegister(request, mobile, userName, shareId, null, null, null, null, null, null, null, null);
            if (netState.getErrorCode() == 2000) {
                Subscribers nextSub = subscribersService.selectBySubscribers(mobile, sub.getParentid());
                newId = nextSub.getId();
                netState.setErrorCode(NetState.SUCCESS_CONN);
                netState.setData("注册成功");
            } else {
                netState.setErrorCode(NetState.ERROR_OPERATE);
                netState.setData("注册失败");
            }
        }

        netState.setJson(newId);
        return netState;
    }
}
